package com.ocm.gateway.controller;

import com.alibaba.nacos.common.utils.StringUtils;
import io.jsonwebtoken.Claims;
import lombok.AllArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import com.ocm.gateway.filter.AuthFilter;
import com.ocm.gateway.provider.AuthProvider;
import com.ocm.gateway.utils.JwtUtil;
import org.springframework.http.server.reactive.ServerHttpRequest;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;
import reactor.core.publisher.Mono;

import javax.annotation.Resource;

/**
 * Author:   hqy
 * Date:     2021/11/7 15:23
 * Description:
 */
@Slf4j
@RestController
@AllArgsConstructor
public class ApiReloadController {

	@Resource
	AuthFilter authFilter;

	@GetMapping("/reloadApi")
	public Mono reloadApi(ServerHttpRequest request){
		try {
			//登录访问 权限访问均需令牌 解析令牌 判断是否登录有效
			String headerToken = request.getHeaders().getFirst(AuthProvider.AUTH_KEY);
			String paramToken = request.getQueryParams().getFirst(AuthProvider.AUTH_KEY);
			if(StringUtils.isBlank(headerToken) && StringUtils.isBlank(paramToken))
				return Mono.error(new RuntimeException("载入失败，原因：未找到有效登录信息"));
			String auth = StringUtils.isBlank(headerToken) ? paramToken : headerToken;
			String token = JwtUtil.getToken(auth);
			Claims claims = JwtUtil.parseJWT(token);
			String role_name = (String) claims.get("role_name");
			if(role_name.contains("administrator")){
				authFilter.init();
				return Mono.just("成功");
			}


			return Mono.error(new RuntimeException("载入失败，原因：您没有权限"));

		} catch (Exception e) {
			return Mono.error(new RuntimeException("载入失败，原因："+e));
		}



	}


}
